package com.sofar.mybatisplus.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author shiguorang
 * @version 1.0.0
 * @ClassName MyMetaObjectHandler
 * @Description TODO
 * @createTime 2022年08月31日 15:42:00
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
//        判断是否存在该字段，有的表没有，没有不用执行填充代码，避免资源浪费
        boolean createTime = metaObject.hasSetter("createTime");
        boolean updateTime = metaObject.hasSetter("updateTime");
        log.info("start insert fill ....");
        if (createTime){
//            填充的类型要和实体类的类型要一直，例如实体类是Date，填充是LocalDateTime，最后填充结果为null
            this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        }
        if (updateTime){
            this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        }

    }

    /**
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        boolean updateTime = metaObject.hasSetter("updateTime");
        if (updateTime){
            log.info("start update fill ....");
            this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        }

    }
}
